package org.zephyr.fastboot.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.context.annotation.Configuration;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author: ZephyrGao
 * @Date: 2024/6/18 18:08
 * @Description: JwtUtil工具类
 */
@Configuration
public class JwtUtil {
    // 30 秒
    private static final long EXPIRATION_TIME = 86400000;// 1天
    private static final String SECRET_KEY = "fastboot3";
    // 1 hour
//    private static long EXPIRATION_TIME = 3600000 * 1;
    // 一天
//    private static long EXPIRATION_TIME = 3600000 * 1;
//private static long EXPIRATION_TIME = 10000 * 10;
//    private static String SECRET = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSSSd";// 秘钥
    // 使用Base64编码的密钥
//    private static final String SECRET = Base64.getEncoder().encodeToString("MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSSSd".getBytes());

//    private static final String USER_ID = "id";

    // 生成JWT令牌
    public static String generateToken(String username) {
        return Jwts.builder().setSubject(username).setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)).signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact();
//        HashMap<String, Object> map = new HashMap<>();
//        // you can put any data in the map
//        map.put(USER_ID, id);
//        // 1. setClaims(map)：将map中的数据存储到Claims中
//        // 2. setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))：设置过期时间
//        // 3. signWith(SignatureAlgorithm.HS512, SECRET)：设置加密算法和密钥
//        // 4. compact()：生成token
//        return Jwts.builder()
//                .setHeaderParam("typ", "JWT")
//                .setClaims(map)
//                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
//                .signWith(SignatureAlgorithm.HS512, SECRET)
//                .compact();
    }

    // 从令牌中获取Claims
    public static Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    // 从令牌中获取用户名
    public static String getUsernameFromToken(String token) {
        return getClaimsFromToken(token).getSubject();
    }

    // 判断令牌是否过期
    public static boolean isTokenExpired(String token) {
        Date expiration = getClaimsFromToken(token).getExpiration();
        return expiration.before(new Date());
    }



//    /**
//     * 校验jwtToken
//     *
//     * @param token
//     * @return
//     */
    // 优化验证逻辑
//    public static String validateToken(String token) {
////        Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
////        return claims.get(USER_ID, String.class);
////        // 使用自定义异常
////        if (StringUtils.isBlank(token)) {
////            throw new JwtValidationException(ResultType.UNAUTHORIZED.getCode(), "Token为空");
////        }
////        try {
////            Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
////            return claims.get(USER_ID, String.class);
////        } catch (ExpiredJwtException e) {
////            throw new JwtValidationException(ResultType.AGAIN_LOGIN.getCode(), "Token已过期，请重新登录");
////        } catch (JwtException e) {
////            throw new JwtValidationException(ResultType.UNAUTHORIZED.getCode(), "无效的Token");
////        }
//    }

    public static void main(String[] args) {
        String id = "hahaha15";

        String token = generateToken(id);
        System.out.println(token);

        //token = "eyJhbGciOiJIUzUxMiJ9.eyJpZCI6IjY4NzZhYjFmYjk0MmZkNGYyN2Zm";
//        id = validateToken(token);
        System.out.println(id);
//        HashMap<String, Object> map = new HashMap<>();
//        // you can put any data in the map
//        map.put("name", id);
//        token = Jwts.builder().setClaims(map).setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
//                .signWith(SignatureAlgorithm.HS512, SECRET).compact();
//
//         String result = "";
//        try {
//
//            result = validateToken(token);
//            System.out.println(result);
//        }catch (Exception e){
//            System.out.println(e.toString());
//        }

    }
}

